// pages/Inventory/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    Taglist: [],
    deviceId: "",
    serviceId: "",
    writeCharacteristicId: "",
    readCharacteristicId: "",
    notifyCharacteristicId: "",
    notify: false,
    services: [],
    characteristics: [],
    connectDeviceIndex: 0,
    connectCharacteristic: 0,
    readServices:[],
    readcharacteristics:[]
  },
  Inventory: function () {
    var that = this;
    that.setData({
      Taglist: []
    })
    var deviceId = getApp().data.deviceId;//全局变量
    console.log("deviceId:" + deviceId)
    that.setData({
      deviceId: deviceId
    })
    if (deviceId == "") {
      wx.showModal({
        title: '提示',
        content: '未连接蓝牙设备,请连接蓝牙设备',
      })
      return
    }
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
      deviceId: that.data.deviceId,
      success: function (res) {
        console.log('device services:', res);
        that.setData({
          services: res.services
        });
        that.loopConnect(that.data.connectDeviceIndex);
      }
    });
    var tag = "";
    var TaglistArray = that.data.Taglist
    that.ax()
    // that.readdata();
  },
  ax: function(){
    var that = this;
    wx.onBLECharacteristicValueChange(function (res) {
      var TaglistArray = that.data.Taglist;
      //处理数据，将Arraybuffer转换为base64，在将base64转换为字符串              
      var base64 = require("base64.modified.js");
      var base64str = base64.decode(wx.arrayBufferToBase64(res.value))//base64解密            
      TaglistArray.push(base64str)
      that.setData({
        Taglist: TaglistArray,
      })
      console.log('TaglistArray: ' + TaglistArray)
    })
  },
  ab2hex:function(buffer){
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },
  readdata:function(){
    var that = this;
    
    wx.readBLECharacteristicValue({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  [**new**]
      deviceId: that.data.deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: that.data.serviceId,
      // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
      characteristicId: that.data.readCharacteristicId,
      success: function (res) {
        console.log('readBLECharacteristicValue:', res)
      }
    });
  },

  loopConnect: function (index) {
    var that = this;
    if (index >= that.data.services.length){
      console.log('services loop end');
      return
    }
    var serviceId = that.data.services[index].uuid//设置serviceId的值     
    that.setData({
      serviceId: serviceId
    })
    wx.getBLEDeviceCharacteristics({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId: that.data.deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: that.data.serviceId,
      success: function (res) {
        console.log('device getBLEDeviceCharacteristics:', res.characteristics);
        that.setData({
          characteristics: res.characteristics
        });
        that.loopCharacteristics(0);
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },

  loopCharacteristics: function (y) {
    var that = this;
    if (y >= this.data.characteristics.length){
      var next = this.data.connectDeviceIndex + 1;
      this.setData({
        connectDeviceIndex: next
      });
      that.loopConnect(that.data.connectDeviceIndex);
      return;
    }
    var characteristic = this.data.characteristics[y];
    //characteristic.properties.read && 
    if (characteristic.properties.notify) {
      console.log('start notify');
      // if (!that.data.notify) {
      //   that.setData({
      //     notify: true
      //   });
      // } else {
      //   return;
      // }
      that.setData({
        readCharacteristicId: characteristic.uuid,
      });
      that.setData({
        notifyCharacteristicId: characteristic.uuid,
      });
      wx.notifyBLECharacteristicValueChange({
        state: true, // 启用 notify 功能
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  
        deviceId: that.data.deviceId,
        // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接s口中获取
        serviceId: that.data.serviceId,
        // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
        characteristicId: that.data.notifyCharacteristicId,
        success: function (res) {
          console.log('notifyBLECharacteristicValueChange success', res.errMsg);
          // 必须在这里的回调才能获取
          var isContains = that.contains(that.data.readServices, that.data.serviceId);
          var isContainsC = that.contains(that.data.readcharacteristics, that.data.notifyCharacteristicId);
          if (!(isContains && isContainsC)){
            var arr = that.data.readServices;
            arr.push(that.data.serviceId);
            that.setData({
              readServices: arr
            });
            var arr = that.data.readcharacteristics;
            arr.push(that.data.serviceId);
            that.setData({
              readcharacteristics: arr
            });
            wx.readBLECharacteristicValue({
              // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  [**new**]
              deviceId: that.data.deviceId,
              // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
              serviceId: that.data.serviceId,
              // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
              characteristicId: that.data.readCharacteristicId,
              success: function (res) {
                console.log('readBLECharacteristicValue:', res)
                console.log("serviceId: " + that.data.serviceId + " readCharacteristicId: " + that.data.readCharacteristicId);
              }
            });
          }                                          
        },
        fail: function (res) {
          console.log('notifyBLECharacteristicValueChange fail', res.errMsg)
        },
        complete: function(res){
          //下一个
          var next = that.data.connectCharacteristic + 1;
          that.setData({
            connectCharacteristic: next
          });
          that.loopCharacteristics(that.data.connectCharacteristic);
        }
      })
    } else {
      var next = this.data.connectCharacteristic + 1;
      this.setData({
        connectCharacteristic: next
      });
      this.loopCharacteristics(this.data.connectCharacteristic);
    }
  },

  contains : function (arr, obj) {  
    var i = arr.length;  
    while(i--) {
      if (arr[i] === obj) {
        return true;
      }
    }  
    return false;  
  }  ,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  isInArray: function (arr, value) {
    for (var i = 0; i < arr.length; i++) {
      if (value === arr[i]) {
        return true;
      }
    }
    return false;
  },
})